import {v4 as uuidv4} from 'uuid';
import Base64 from 'base-64';
import CryptoJS from '../node_modules/crypto-js/crypto-js.js'
import md5 from 'js-md5'
	import * as utf8 from "utf8"
	
const install = (Vue, vm) => {
	
	
	// 通用请求头设定
	const ajaxHeader = 'x-ajax';
	const sessionIdHeader = 'mini-user-login-token';
	const rememberMeHeader = 'x-remember';

	

	
	let info = null;
	let publicKey =
		`MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEPqHavyfprY52X/RFbuTq8qz9rLnbGPYMTgKZNL2dAp+1lj0zuwJyPf35/Icu1iO0iFps8lJ089oNCJNh1FXKs+sje0bXQIxFr0axmKtaeWzErD/9Iv5hvq01s1sPjZ3x4fvCvStue2rbXlWbm+PmtVssjsBbMajkbgghmM2RwQIDAQAB`
	// 此处第二个参数vm，就是我们在页面使用的this，你可以通过vm获取vuex等操作
	uni.getSystemInfo({
		success: function(res) {info = res}
	});
	/* 参数排序 */
	function getSortParamsString(params) {
		
		const keys = Object.keys(params).sort();
		
		const sortParamsFull = {};
		let sortParamsMini = {};
		for (let i = 0; i < keys.length; i++) { // 遍历keys数组
			const val = params[keys[i]];
			sortParamsFull[keys[i]] = val
			
		}

		// 对对象的键进行排序
		let sortedKeys = Object.keys(params).sort();
		// 使用 reduce 方法过滤空值
		 sortParamsMini = sortedKeys.reduce((acc, key) => {
		    // 检查值是否为空字符串、空数组、空对象或 undefined
		    if (
		        params[key] !== "" &&
		        !(Array.isArray(params[key]) && params[key].length === 0) &&
		        !(typeof params[key] === "object" && Object.keys(params[key]).length === 0) &&
		        params[key] !== undefined
		    ) {
		        acc[key] = params[key]; // 将非空值添加到新对象中
		    }
		    return acc;
		}, {});
		
		const filteredArr = {};
		for (const key in sortParamsMini) {
		  if (!Array.isArray(sortParamsMini[key])) {
		    filteredArr[key] = sortParamsMini[key];
		  }
		}
		
		//判断对象包含中文需要先进行编码
		
		console.log(processChineseValues(sortParamsFull),'@@@@@@@@@@@@@@@');
		
		
		return {
			full: JSON.stringify(processChineseValues(sortParamsFull)),
			mini: JSON.stringify(filteredArr)
			// mini: JSON.stringify(processChineseValues(filteredArr))
		};
	}
	

	// 判断字符串中是否包含中文字符的函数
	function hasChinese(str) {
	  return /[\u4E00-\u9FA5\uF900-\uFA2D]/.test(str);
	}
	
	// 遍历对象的所有值，对包含中文字符的值进行特殊处理
	function processChineseValues(obj) {
	  for (const key in obj) {
	    if (typeof obj[key] === 'string' && hasChinese(obj[key])) {
	      obj[key] = utf8.encode(obj[key])
	    }
	  }
	  return obj;
	}



	/* 生成body中的加密数据：使用apiSecret进行RSA加密 */
	function getDesData(apiSecret, sortParamsString) {
		console.log(sortParamsString,'入参加密之前的样子~~~~~~');

		const Base64Data = Base64.encode(sortParamsString)

		const keyHex = CryptoJS.enc.Utf8.parse(apiSecret);
		
		const dataHex = CryptoJS.enc.Utf8.parse(Base64Data)
	
		const encrypted = CryptoJS.DES.encrypt(dataHex, keyHex, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
		
		return encrypted.ciphertext.toString();
	}


	

	// 请求参数默认配置
	Vue.prototype.$u.http.setConfig({
		baseUrl: vm.vuex_config.baseUrl,
		originalData: true,
	});

	// 请求拦截，配置Token等参数
	Vue.prototype.$u.http.interceptor.request = (req) => {
		if (!req.header) {
			req.header = [];
		}
		req.header["source"] = "app";

		// 默认指定返回 JSON 数据
		if (!req.header[ajaxHeader]) {
			req.header[ajaxHeader] = 'json';
		}

		// 设定传递 Token 认证参数 aidex
		if (!req.header[sessionIdHeader] && vm.vuex_token) {
			req.header[sessionIdHeader] = vm.vuex_token.loginToken;
		}

		// 为节省流量，记住我数据不是每次都发送的，当会话失效后，尝试重试登录 aidex
		if (!req.header[rememberMeHeader] && vm.vuex_remember && req.remember) {
			req.header[rememberMeHeader] = vm.vuex_remember;
			req.remember = false;
		}
		// console.log('request', req);
		return req;
	}

	// 响应拦截，判断状态码是否通过
	Vue.prototype.$u.http.interceptor.response = async (res, req) => {
		console.log('response', res);
		let data = res.data;
		if (!(data)) {
			vm.$u.toast('未连接到服务器')
			return false;
		}

		if (typeof data === 'object' && !(data instanceof Array)) {
			if (data.token) {
				vm.$u.vuex('vuex_token', data.token);
				if (data.user) {
					vm.$u.vuex('vuex_user', data.user);
				}
				vm.$u.vuex('vuex_isAgent', data.isAgent);
			}
			
			console.log(res.data.code,'&&&&^^^^^^^^^');
			
			if (res.data.code == '0013' ){
				vm.$u.vuex("vuex_token", '');
				uni.reLaunch({
					url:"/pages/sys/login/index"
				})
				
			}
			
			
			if (res.data.code == 'EXPIRE' ){
				// vm.$u.toast(res.data.msg)
			
				uni.showModal({
				  title: "提示",
				   cancelColor: "#999999",
				  confirmColor: "#FA4A53",
				  // showCancel: false,
				  content: res.data.msg,
				  confirmText: "确定",
				  success: function (res1) {
					  console.log(res1,66666666);
					  if(res1.confirm){
						  uni.navigateTo({
						  	url: "/pages/sys/user/renew"
						  })
					  }
					
				  },
				  fail: function (err) {
				    console.log("fail:" + JSON.stringify(err));
				  },
				});
				
				
				// uni.showModal({
				// 	title: '提示',
				// 	content: res.data.msg,
				// 	showCancel: false,
				// 	success: function () {
				// 		// uni.navigateBack();
				// 	}
				// });
			}
			
			
			
			if (data.result === 'login') {
				vm.$u.vuex('vuex_user', {});
				if (req.tryagain == undefined || req.tryagain) {
					req.tryagain = false;
					req.remember = true;
					await vm.$u.http.request(req).then(res => {
						data = res;
					});
				}
				if (data.result === 'login') {
					if (!req.data.loginCheck) {
						vm.$u.toast(data.msg);
					}
					req.tryagain = true;
				}
			}
		}

		if (res.header && res.header[rememberMeHeader]) {
			let remember = res.header[rememberMeHeader];
			if (remember && remember != 'deleteMe') {
				vm.$u.vuex('vuex_remember', remember);
			} else {
				vm.$u.vuex('vuex_remember', '');
			}
		}

		return data;
	}

	// 封装 get text 请求
	vm.$u.getText = (url, data = {}, header = {}) => {
		return vm.$u.http.request({
			dataType: 'text',
			method: 'GET',
			url,
			header,
			data
		})
	}
	
	
	/* 生成header中签名：使用apiKey进行MD5加密 */
	function getMd5Sign(apiSecret, requestId, dateTimestamp, sortParamsString) {
		const str = `${apiSecret}:${requestId}:${dateTimestamp}:` + sortParamsString
		
		// console.log('签名字符串拼接',JSON.stringify(str,null,2));
		// console.log('33333签名字符串拼接',str);
		return md5(str);
	}
	

	// 封装 post json 请求
	vm.$u.postJson = (url, data = {}, header = {},showLoading=true) => {
		
		console.log(showLoading,'$$$$$$$$$$$$$');
		const uuid = uuidv4()
		const timestamp = new Date().getTime()
		console.error(timestamp,'**********************');

		const sortParamsObject = getSortParamsString(data == null || data == undefined ? {} : data);
		
		
		let headerParams = {
			'content-type': 'application/json;charset=UTF-8',
			'x-app-id': '2319829165',
			'x-timestamp':timestamp ,
			'x-tenant-id': '1',
			'x-encrypt-type': 'des',
			'osName': info.osName,
			'appVersion': info.appVersion,
			'osVersion': info.osVersion,
			'deviceBrand': info.deviceBrand,
			'deviceModel': info.deviceModel
		}
		
		
		const sign = getMd5Sign(publicKey, uuid, timestamp, sortParamsObject.mini)
		
		console.error(timestamp, sign,'signsignsignsign*******');
		
		return vm.$u.http.request({
			url,
			
			method: 'POST',
			header: {
				...headerParams,
				'x-request-id':uuid,
				'x-sign': sign,
			},
			data: getDesData(publicKey, sortParamsObject.full),
			showLoading,
		})
	}

}

export default {
	install
}
